// pages/subpackage/pages/crm/chart/chart.js
import * as echarts from '../../../components/ec-canvas/echarts';

var app = getApp();

var lineChart; //统计表
var barChart; //工单状态
var pieOrderType; //工单类型完成量
var pieEngineer; //工程人员完单量
var barChartAge; //年龄百分比
var client;//1总后台2运营端3城市合伙人

Page({

  /**
   * 页面的初始数据
   */
  data: {
    noticesList:{},
    chartActive: 1, //统计，1订单统计、2金额统计、3用户统计
    todayActive: 1, //工单状态，1今日、2全部
    orderActive: 1, //工单，1已完成、2待处理
    rankActive: 1, //排行，1运营中心、2城市合伙人
    ecLine: { //统计表
      onInit: function (canvas, width, height, dpr) {
        lineChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(lineChart);
        lineChart.setOption(getLineOption(), true);

        return lineChart;
      }
    },
    ecBar: { //工单状态
      onInit: function (canvas, width, height, dpr) {
        barChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(barChart);
        barChart.setOption(getBarOption(), true);

        return barChart;
      }
    },

    ecPieOrderType: { //工单类型完成量
      onInit: function (canvas, width, height, dpr) {
        pieOrderType = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(pieOrderType);
        pieOrderType.setOption(getPieOrderType(), true);

        return pieOrderType;
      }
    },

    ecPieEngineer: { //工程人员完单量
      onInit: function (canvas, width, height, dpr) {
        pieEngineer = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(pieEngineer);
        pieEngineer.setOption(getPieEngineer(), true);

        return pieEngineer;
      }
    },

    ecBarAge: { //年龄百分比
      onInit: function (canvas, width, height, dpr) {
        barChartAge = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(barChartAge);
        barChartAge.setOption(getBarAgeOption(), true);

        return barChartAge;
      }
    },

    dataInfo: '', //所有数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      client: that.options.client,
    })
    this.getData();
    this.getnoticelists();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  getnoticelists: function () {
    var that = this;
    // ajax请求
    app.ajax({
      url: 'api/announcement/getlists',
      url_type: 2,
      data: {
        page: 1,
        pageSize: 1,
        key: '',
      },
      success: function (res) {
        var newlist = '';//newlist(过渡)
        if (res.data.code == 1000) {
          that.setData({
            noticesList: res.data.data[0],
          })
        } else {
        }

      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getData();
  },

  //获取详情
  getData(){
    var that = this;
    app.ajax({
      url: 'api/Statistics/getTotalData',
      url_type: 2,
      data: {
        time_id: 1,
      },
      success: function (res) {
        wx.stopPullDownRefresh();
        if (res.data.code == 1000) {
          var data = res.data.data;
          that.setData({
            dataInfo: data
          })

          setTimeout(()=>{
            // ----- 统计表 ------
            var set_order_data_num = data.order_data.seven_everyday_order_num; //订单统计
            var set_order_data_money = data.order_data.seven_everyday_money_num; //金额统计
            var set_customer_data_num = data.customer_data.seven_everyday_customer_num; //用户统计
            var xData = data.seven;
            lineChart.setOption({
              xAxis: {
                data: xData
              },
              series: [{
                data: that.data.chartActive == 1 ? set_order_data_num : that.data.chartActive == 2 ? set_order_data_money : set_customer_data_num
              }]
            });

            // ----- 工单状态 ------
            var all = data.work_data.all;
            var today = data.work_data.today;
            //已完成
            var all_complete = [all.new_complete, all.core_complete, all.fee_complete, all.repair_complete, all.moving_complete, all.dismant_complete, all.contract_complete];
            var today_complete = [today.new_complete, today.core_complete, today.fee_complete, today.repair_complete, today.moving_complete, today.dismant_complete, today.contract_complete];
            //待处理
            var all_stay = [all.new_stay, all.core_stay, all.fee_stay, all.repair_stay, all.moving_stay, all.dismant_stay, all.contract_stay];
            var today_stay = [today.new_stay, today.core_stay, today.fee_stay, today.repair_stay, today.moving_stay, today.dismant_stay, today.contract_stay];
            barChart.setOption({
              series: [{
                data: that.data.todayActive == 2 ? all_complete : today_complete //已完成
              }, {
                data: that.data.todayActive == 2 ? all_stay : today_stay //待处理
              }]
            });

            // ----- 工单类型完成量 ------
            var all_complete_pie = [
              { value: all.new_complete, name: '新装' }, 
              { value: all.core_complete, name: '换芯' }, 
              { value: all.repair_complete, name: '维修' }, 
              { value: all.moving_complete, name: '移机' }, 
              { value: all.dismant_complete, name: '拆机' }
            ];
            var all_stay_pie = [
              { value: all.new_stay, name: '新装' },
              { value: all.core_stay, name: '换芯' },
              { value: all.repair_stay, name: '维修' },
              { value: all.moving_stay, name: '移机' },
              { value: all.dismant_stay, name: '拆机' }
            ];
            pieOrderType.setOption({
              series: [{
                data: that.data.orderActive == 1 ? all_complete_pie : all_stay_pie 
              }]
            });
            
            // ----- 工程人员完单量 ------
            var engineer_order = data.staff_complete_work_count;
            var engineer_order_data = [];
            engineer_order.forEach((item,index)=>{
              if(index < 5) {
                engineer_order_data.push({ value: item.count, name: item.engineers_name });
              }
            });
            pieEngineer.setOption({
              series: [{
                data: engineer_order_data
              }]
            });

            // ----- 年龄百分比 ------
            var age_range_data = [data.customer_age.twenty_to_twenty_five, data.customer_age.twenty_six_to_thirty, data.customer_age.thirty_one_to_forty, data.customer_age.forty_one_to_fifty, data.customer_age.fifty_to_sixty];
            for (var i = 0; i < age_range_data.length;i++){
              const ind_x = age_range_data[i].lastIndexOf("%");
              age_range_data[i] = age_range_data[i].substring(0, ind_x);
            }
            barChartAge.setOption({
              series: [{
                data: age_range_data
              }]
            });
          }, 500)
        } else {
          app.showToast(res.data.msg, "none", 2000, function () { });
          return false;
        }
      }
    });
  },

  //切换统计
  checkTotalChart(e){
    var type = e.currentTarget.dataset.type;
    this.setData({
      chartActive: type
    })
    var set_order_data_num = this.data.dataInfo.order_data.seven_everyday_order_num; //订单统计
    var set_order_data_money = this.data.dataInfo.order_data.seven_everyday_money_num; //金额统计
    var set_customer_data_num = this.data.dataInfo.customer_data.seven_everyday_customer_num; //用户统计
    lineChart.setOption({
      xAxis: {
        data: this.data.dataInfo.seven
      },
      series: [{
        data: type == 1 ? set_order_data_num : type == 2 ? set_order_data_money : set_customer_data_num
      }]
    });
  },
  //切换工单状态
  checkToday(e){
    var type = e.currentTarget.dataset.type;
    this.setData({
      todayActive: type
    })

    var all = this.data.dataInfo.work_data.all;
    var today = this.data.dataInfo.work_data.today;
    //已完成
    var all_complete = [all.new_complete, all.core_complete, all.fee_complete, all.repair_complete, all.moving_complete, all.dismant_complete, all.contract_complete];
    var today_complete = [today.new_complete, today.core_complete, today.fee_complete, today.repair_complete, today.moving_complete, today.dismant_complete, today.contract_complete];
    //待处理
    var all_stay = [all.new_stay, all.core_stay, all.fee_stay, all.repair_stay, all.moving_stay, all.dismant_stay, all.contract_stay];
    var today_stay = [today.new_stay, today.core_stay, today.fee_stay, today.repair_stay, today.moving_stay, today.dismant_stay, today.contract_stay];
    barChart.setOption({
      series: [{
        data: type == 2 ? all_complete : today_complete //已完成
      }, {
        data: type == 2 ? all_stay : today_stay //待处理
      }]
    });
  },
  //切换工单
  checkOrder(e){
    var type = e.currentTarget.dataset.type;
    this.setData({
      orderActive: type
    })
    var all = this.data.dataInfo.work_data.all;
    var all_complete_pie = [
      { value: all.new_complete, name: '新装' },
      { value: all.core_complete, name: '换芯' },
      { value: all.repair_complete, name: '维修' },
      { value: all.moving_complete, name: '移机' },
      { value: all.dismant_complete, name: '拆机' }
    ];
    var all_stay_pie = [
      { value: all.new_stay, name: '新装' },
      { value: all.core_stay, name: '换芯' },
      { value: all.repair_stay, name: '维修' },
      { value: all.moving_stay, name: '移机' },
      { value: all.dismant_stay, name: '拆机' }
    ];
    pieOrderType.setOption({
      series: [{
        data: type == 1 ? all_complete_pie : all_stay_pie
      }]
    });
  },
  //切换排行榜
  checkRank(e){
    this.setData({
      rankActive: e.currentTarget.dataset.type
    })
  },
  //跳转 公告
  noticeList(){
      wx.navigateTo({
        url: '../noticeList/noticeList',
      })
  },
})

//统计表
function getLineOption() {
  return {
    grid: {
      x: "12%",//x 偏移量
      y: "7%", // y 偏移量
      width: "85%", // 宽度
      height: "79%"// 高度
    },
    xAxis: {
      type: 'category',
      data: ["05.03"], //['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisLabel: { 
        color: '#404447', //刻度标签文字的颜色
        fontSize: '12',
        interval: 0, //坐标轴刻度标签的显示间隔
      }, 
      axisTick: { show: false }, //隐藏刻度线
    },
    yAxis: {
      type: 'value',
      splitLine:{
        lineStyle: { //坐标轴线线样式
          color: '#EFF4FD',
          type: 'dashed'
        },
      },
      axisTick: { show: false }, //隐藏刻度线
    },
    series: [{
      data: [0],
      type: 'line',
      smooth: true, //是否平滑曲线显示
      lineStyle: { color: "#FB9D15" }, //线条样式
      itemStyle: { opacity: 0 }, //折线拐点标志的样式
      areaStyle: {  //区域填充样式
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: '#FEF4E7' // 0% 处的颜色
          }, {
              offset: 1, color: '#FFFDF9' // 100% 处的颜色
          }]
        }
      } 
    }]
  };
}

//工单状态
function getBarOption() {
  return {
    grid: {
      x: "12%",//x 偏移量
      y: "7%", // y 偏移量
      width: "85%", // 宽度
      height: "79%"// 高度
    },
    xAxis: {
      type: 'category',
      data: ['新装', '换芯', '催费', '维修', '移机', '拆机', '签约'],
      axisLabel: {
        color: '#404447', //刻度标签文字的颜色
        fontSize: '12',
        interval: 0, //坐标轴刻度标签的显示间隔
      },
      axisTick: { show: false }, //隐藏刻度线
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: { //坐标轴线线样式
          color: '#EFF4FD',
          type: 'dashed'
        },
      },
      axisTick: { show: false }, //隐藏刻度线
    },
    series: [{
      data: [0], //[120, 200, 150, 80, 70, 110, 130],
      type: 'bar',
      barWidth: 12, //柱条的宽度，不设时自适应
      itemStyle: { 
        color: new echarts.graphic.LinearGradient(
          0, 0, 0, 1,
          [
            { offset: 0, color: '#FBA900' },
            { offset: 1, color: '#FB765E' }
          ]
        ), //背景色
        barBorderRadius: [6, 6, 0, 0] //圆角半径（顺时针左上，右上，右下，左下）
      },
    }, {
      data: [0],//[20, 50, 90, 30, 0, 40, 80],
      type: 'bar',
      barWidth: 12, //柱条的宽度，不设时自适应
      itemStyle: { 
        color: new echarts.graphic.LinearGradient(
          0, 0, 0, 1,
          [
            { offset: 0, color: '#9182FE' },
            { offset: 1, color: '#53A0F9' }
          ]
        ), //背景色
        barBorderRadius: [6, 6, 0, 0] //圆角半径（顺时针左上，右上，右下，左下）
      },
    }]
  };
}

//工单类型完成量
function getPieOrderType() {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      left: 12,
      bottom: 5,
      data: ['新装', '换芯', '维修', '移机', '拆机'],
      icon: 'circle',
      itemWidth: 12,
      itemHeight: 8,
      itemGap: 10
    },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['50%', '40%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  };
}

//工程人员完单量
function getPieEngineer() {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)',
    },
    legend: {
      left: 12,
      bottom: 5,
      //data: [],//['小王', '小李', '小郑', '小刘'],
      icon: 'circle',
      itemWidth: 12,
      itemHeight: 8,
      itemGap: 10
    },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['50%', '40%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  };
}

//年龄百分比
function getBarAgeOption() {
  return {
    grid: {
      x: "12%",//x 偏移量
      y: "7%", // y 偏移量
      width: "85%", // 宽度
      height: "79%"// 高度
    },
    xAxis: {
      type: 'category',
      data: ['20-25', '26-30', '31-40', '41-50', '51-60'],
      axisLabel: {
        color: '#404447', //刻度标签文字的颜色
        fontSize: '12',
        interval: 0, //坐标轴刻度标签的显示间隔
      },
      axisTick: { show: false }, //隐藏刻度线
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: { //坐标轴线线样式
          color: '#EFF4FD',
          type: 'dashed'
        },
      },
      axisTick: { show: false }, //隐藏刻度线
    },
    series: [{
      data: [0],//[120, 200, 150, 80, 70],
      type: 'bar',
      barWidth: 14, //柱条的宽度，不设时自适应
      itemStyle: {
        color: new echarts.graphic.LinearGradient(
          0, 0, 0, 1,
          [
            { offset: 0, color: '#FFD074' },
            { offset: 1, color: '#FF580F' }
          ]
        ), //背景色
        barBorderRadius: [7, 7, 0, 0] //圆角半径（顺时针左上，右上，右下，左下）
      },
    }]
  };
}